package com.module.ble.db

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.module.ble.db.table.UserSportRecord
import kotlinx.coroutines.flow.Flow

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/04/16
 *
 * 描述：
 *
 * 修订历史：
 *
 */
@Dao
interface SportRecordDao {

    @Delete
    fun delete(data: UserSportRecord)

    @Query("SELECT * FROM sport_record WHERE startTs = :time")
    fun findByTime(time : Long): UserSportRecord?

    @Query("select * from sport_record")
    fun findAll(): MutableList<UserSportRecord>

    @Query("select * from sport_record WHERE sysStat = 0 AND endTs > 0")
    fun findAllNotUp(): MutableList<UserSportRecord>

    @Query("SELECT * FROM sport_record")
    fun findAllFlow(): Flow<List<UserSportRecord>>

    /**
     * 根据传入时间戳查询该时间戳当天内的所有运动记录数据
     * @param timestamp 指定的时间戳（毫秒）
     * @return 当天所有的运动记录数据列表
     */
//    @Query("SELECT * FROM sport_record WHERE date(startTs/1000, 'unixepoch', 'localtime') = date(:timestamp/1000, 'unixepoch', 'localtime') ORDER BY startTs ASC")
//    @Query("SELECT * FROM sport_record WHERE date(startTs/1000, 'unixepoch', 'localtime') = date(:timestamp/1000, 'unixepoch', 'localtime') AND startTs > 0 AND endTs > 0 ORDER BY startTs ASC")
    @Query("SELECT * FROM sport_record WHERE date(startTs/1000, 'unixepoch', 'localtime') = date(:timestamp/1000, 'unixepoch', 'localtime') AND duration >= 60 ORDER BY startTs ASC")
    fun findAllByDay(timestamp: Long): List<UserSportRecord>

    /**
     * 根据传入时间戳查询该时间戳当天内的所有运动记录数据（Flow版本）
     * @param timestamp 指定的时间戳（毫秒）
     * @return Flow<List<UserSportRecord>> 当天所有的运动记录数据
     */
    @Query("SELECT * FROM sport_record WHERE date(startTs/1000, 'unixepoch', 'localtime') = date(:timestamp/1000, 'unixepoch', 'localtime') ORDER BY startTs ASC")
    fun findAllByDayFlow(timestamp: Long): Flow<List<UserSportRecord>>

    /**
     * 根据传入ID查询该运动记录数据
     * @param id ID
     * @return 当前ID运动记录数据
     */
    @Query("SELECT * FROM sport_record WHERE startTs =:id")
    fun findAllById(id: Long): UserSportRecord?

    @Query("select count(*) from sport_record")
    fun count(): Int

    @Insert(onConflict = OnConflictStrategy.REPLACE)//新数据更新旧数据
    fun insertOrUpdate(vararg bean: UserSportRecord)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(mList:List<UserSportRecord>)

    @Update
    fun update(mList:List<UserSportRecord>)

    @Query("DELETE FROM sport_record")//删除所有
    fun deleteAll()

    /**
     * 将所有数据的sysStat更新为0
     */
    @Query("UPDATE sport_record SET sysStat = 0")
    fun updateAllSysStatToZero()

    /**
     * 删除所有startTs或endTs小于0的无效数据
     */
    @Query("DELETE FROM sport_record WHERE startTs <= 0 OR endTs <= 0")
    fun deleteInvalidData()
}